//
//  LaunchViewHelper.m
//  TestTable
//
//  Created by 刘转 on 2018/8/29.
//  Copyright © 2018年 刘转. All rights reserved.
//

#import "LaunchViewHelper.h"
#import "LZLaunchView.h"

#define kUserDefaults [NSUserDefaults standardUserDefaults]
@implementation LaunchViewHelper
+(void)loadLaunchViewInwindow:(UIWindow*)window{
    // 1.判断沙盒中是否存在广告图片，如果存在，直接显示
    NSString *filePath = [[self class] getFilePathWithImageName:[kUserDefaults valueForKey:adImageName]];
    NSLog(@"+++%@",filePath);
    BOOL isExist = [[self class] isFileExistWithFilePath:filePath];
    [[NSUserDefaults standardUserDefaults] setBool:isExist forKey:@"adisExist"];
    if (isExist) {// 图片存在
        LZLaunchView *advertiseView = [[LZLaunchView alloc] initWithFrame:window.bounds];
        advertiseView.filePath = filePath;
        [advertiseView show];
        
    }
    // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
    [[self class] getAdvertisingImage];
}
/**
 *  判断文件是否存在
 */
+ (BOOL)isFileExistWithFilePath:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}
/**
 *  初始化广告页面
 */
+ (void)getAdvertisingImage
{
    // 请求广告接口
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/app/app.ashx?action=config&companyid=%@",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        
        if ([responseObject[@"status"] intValue] == 1) {
            NSDictionary *adDic = responseObject[@"appAd"];
            NSString *imageUrl = [NSString stringWithFormat:@"http:%@",adDic[@"photoPath"]];
            NSString * imageName = [imageUrl componentsSeparatedByString:@"/"].lastObject;
            // 保存APP状态
            [UserDefaults setValue:[NSNumber numberWithInt:[responseObject[@"appStatus"] intValue]]  forKey:@"appStatus"];
            // APP安装统计appTongji，0 不开启 1 开启
            if ([responseObject[@"appTongji"] intValue] == 1) {
                if (!([[UserDefaults valueForKey:@"saveTongJi"] intValue] == 1)) {
                    
                    [[self class] statisticalnstallationNum];
                }
            }
            // 拼接沙盒路径
            NSString *filePath = [[self class] getFilePathWithImageName:imageName];
            BOOL isExist = [[self class] isFileExistWithFilePath:filePath];
            if (!isExist){ // 如果该图片不存在，则删除老图片，下载新图片
                
                [[self class] downloadAdImageWithUrl:imageUrl imageName:imageName];
                // 保存广告链接
                if ([adDic[@"photoConType"] intValue] == 1) {
                    // 跳转链接
                    [kUserDefaults setValue:adDic[@"photoLink"] forKey:adUrl];
                    [kUserDefaults synchronize];
                } else {
                    [kUserDefaults removeObjectForKey:adUrl];
                    [kUserDefaults synchronize];
                }
            }
        }
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark - 统计APP安装
+ (void)statisticalnstallationNum
{
    // 判断是否开启限制广告追踪
    NSString *appkey;
    if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
        // 返回YES说明没有 “开启限制广告跟踪”,如果返回的是NO，说明等待你的就是一串00000000000
        //        NSLog(@"idfa-----%@",[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]);
        appkey = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    } else {
        //        NSLog(@"SimulateIDFA-----%@",[SimulateIDFA createSimulateIDFA]);
        appkey = [SimulateIDFA createSimulateIDFA];
    }
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    NSLog(@"--------%@",@{@"appos":@"IOS",@"appkey":appkey,@"appipaddress":[[self class] getIPAddress]});
    [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/app/app.ashx?action=tongji&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"appos":@"IOS",@"appkey":appkey,@"appipaddress":[[self class] getIPAddress]} success:^(id responseObject) {
        if ([responseObject[@"status"] intValue] == 1) {
            [UserDefaults setObject:@"1" forKey:@"saveTongJi"];
        }
    } failure:^(NSError *error) {
        NSLog(@"error-----%@",error);
        
    }];
}
/**
 *  下载新图片
 */
+ (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString: imageUrl]];
            UIImage *image = [UIImage imageWithData:data];
            
            NSString *filePath = [[self class] getFilePathWithImageName:imageName]; // 保存文件的名称
            
            if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) { // 保存成功
                NSLog(@"保存成功");
                [self deleteOldImage];
                [kUserDefaults setValue:imageName forKey:adImageName];
                [kUserDefaults synchronize];
                // 如果有广告链接，将广告链接也保存下来
                
            }else{
                NSLog(@"保存失败");
            }
        });
        
    });
}
/**
 *  删除旧图片
 */
+ (void)deleteOldImage
{
    NSString *imageName = [kUserDefaults valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [[self class] getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}
/**
 *  根据图片名拼接文件路径
 */
+ (NSString *)getFilePathWithImageName:(NSString *)imageName
{
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}
//获取手机的网络的ip地址
+ (NSString *)getIPAddress
{
    NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];
    NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:nil];
    return ip;
//    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
//    NSData *data = [NSData dataWithContentsOfURL:ipURL];
//    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//    NSString *ipStr = nil;
//    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
//        ipStr = ipDic[@"data"][@"ip"];
//    }
//    return (ipStr ? ipStr : @"");
}

@end
